package com.nsgf.library.ui.page;

import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.databinding.ActivityVideoPlayerBinding;
import com.nsgf.library.domain.request.AccountRequester;

import java.io.File;

import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.VideoView;

import static io.vov.vitamio.MediaPlayer.VIDEOQUALITY_MEDIUM;

/**
 * 视频播放Activity
 */
public class VideoPlayerActivity extends BaseActivity {

    private VideoPlayerStates mStates;
    private ActivityVideoPlayerBinding mBinding;
    private AccountRequester mAccountRequester;

    private String videoPath;
    private boolean isLandscape = false;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(VideoPlayerStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_video_player, BR.vm, mStates);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityVideoPlayerBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);

        mStates.titleBar.set("视频播放");

        // 初始化Vitamio
        Vitamio.isInitialized(this);

        // 获取视频路径
        if (getIntent() != null) {
            videoPath = getIntent().getStringExtra("videoPath");
        }

        if (videoPath == null || videoPath.isEmpty()) {
            showToast("视频路径不能为空");
            finish();
            return;
        }

        // 设置返回按钮点击事件
        mBinding.titlebar.titleBarBack.setOnClickListener(v -> finish());

        // 初始化视频播放器
        initVideoPlayer();
    }

    /**
     * 初始化视频播放器
     */
    private void initVideoPlayer() {
        VideoView videoView = mBinding.videoView;
        TextView tvLoading = mBinding.tvLoading;

        // 设置视频路径
        String finalVideoPath = videoPath;
        
        // 如果是网络路径，直接使用；如果是本地路径，需要转换为File URI
        if (videoPath.startsWith("http://") || videoPath.startsWith("https://")) {
            // 网络路径，可能需要添加base URL
            if (!videoPath.startsWith("http://") && !videoPath.startsWith("https://")) {
                finalVideoPath = APIs.BASE_URL_IMG + videoPath;
            }
            videoView.setVideoURI(Uri.parse(finalVideoPath));
        } else {
            // 本地文件路径
            File videoFile = new File(videoPath);
            if (videoFile.exists()) {
                videoView.setVideoURI(Uri.fromFile(videoFile));
            } else {
                // 尝试使用网络路径
                finalVideoPath = APIs.BASE_URL_IMG + videoPath;
                videoView.setVideoURI(Uri.parse(finalVideoPath));
            }
        }

        // 设置视频质量
        videoView.setVideoQuality(VIDEOQUALITY_MEDIUM);

        // 设置MediaController
        io.vov.vitamio.widget.MediaController mediaController = new io.vov.vitamio.widget.MediaController(this);
        videoView.setMediaController(mediaController);

        // 设置监听器
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // 视频准备完成，隐藏加载提示
                tvLoading.setVisibility(View.GONE);
                // 开始播放
                videoView.start();
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.e("VideoPlayerActivity", "视频播放错误: what=" + what + ", extra=" + extra);
                tvLoading.setText("视频加载失败");
                showToast("视频播放失败");
                return true;
            }
        });

        videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                switch (what) {
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        // 开始缓冲
                        tvLoading.setVisibility(View.VISIBLE);
                        tvLoading.setText("缓冲中...");
                        break;
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                        // 缓冲结束
                        tvLoading.setVisibility(View.GONE);
                        break;
                    case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                        // 视频延迟
                        Log.d("VideoPlayerActivity", "视频延迟");
                        break;
                }
                return true;
            }
        });

        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // 播放完成
                Log.d("VideoPlayerActivity", "视频播放完成");
            }
        });

        // 请求焦点
        videoView.requestFocus();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBinding.videoView != null) {
            mBinding.videoView.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBinding.videoView != null) {
            mBinding.videoView.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBinding != null && mBinding.videoView != null) {
            mBinding.videoView.stopPlayback();
        }
    }

    /**
     * States
     */
    public static class VideoPlayerStates extends StateHolder {
        public final State<String> titleBar = new State<>("视频播放");
    }
}

